package com.gxpt.app.fragment;

import android.Manifest;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.gxpt.app.AppUtils;
import com.gxpt.app.BaseFragment;
import com.gxpt.app.Constant;
import com.gxpt.app.R;
import com.gxpt.app.bean.newlist_bean;
import com.gxpt.app.bean.upload_bean;
import com.utils.ScreenUtils;
import com.utils.T;
import com.utils.logger.Logger;
import com.utils.okhttputils.HttpUtils;
import com.utils.picasso.PicassoUtils;
import com.utils.v24.v_2_4;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import okhttp3.Call;

/**
 * Created by dufeng on 2017/9/8.
 */

@ContentView(R.layout.fragment_authen_qy)
public class Fragment_authen_qy extends BaseFragment {

    private final int SDK_PERMISSION_REQUEST = 127;

    private static final int NONE                 = 0;
    private static final int PHOTO_GRAPH          = 1;// 拍照
    private static final int PHOTO_ZOOM           = 2; // 缩放
    private static final int PHOTO_RESOULT        = 3;// 结果
    private static final String IMAGE_UNSPECIFIED = "image/*";

    String tmppicPath    = "";
    String cropedpicPath = "";

    Context context;
    Activity mActivity;

    @ViewInject(R.id.toTYPEModel)
    RelativeLayout toTYPEModel;

    @ViewInject(R.id.typeName)
    TextView typeName;

    @ViewInject(R.id.typelayout1)
    LinearLayout typelayout1;

    @ViewInject(R.id.typelayout2)
    LinearLayout typelayout2;

    @ViewInject(R.id.put_shop_name)
    EditText put_shop_name;

    @ViewInject(R.id.put_social_code)
    EditText put_social_code;

    @ViewInject(R.id.put_legal_person)
    EditText put_legal_person;

    @ViewInject(R.id.put_legal_telphone)
    EditText put_legal_telphone;



    @ViewInject(R.id.photo1)
    ImageView photo1;

    @ViewInject(R.id.photo11)
    ImageView photo11;

    @ViewInject(R.id.photo22)
    ImageView photo22;

    @ViewInject(R.id.photo33)
    ImageView photo33;

    @ViewInject(R.id.photo44)
    ImageView photo44;

    @ViewInject(R.id.photo55)
    ImageView photo55;

    @ViewInject(R.id.to_add)
    Button to_add;


    int cert_type = 0;

    String quality_photo    = null;
    String business_license = null;
    String swdj_photo       = null;
    String zzjg_photo       = null;
    String yhkh_photo       = null;

    int photoIndex = 0;
    //临时变量
    Uri photoURI;//相加拍摄保存路径


    int pic_view_width = 0;
    int pic_view_hight = 0;
    @Override
    public void onAttach(Context context) {
        this.context = context;
        super.onAttach(context);
    }

    @Override
    public void onAttach(Activity activity) {
        mActivity = activity;
        super.onAttach(activity);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        View rootView = x.view().inject(this, inflater, container);
        getPersimmions();
        initViews();
        initData();
        return  rootView;
    }

    @TargetApi(23)
    private void getPersimmions() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            ArrayList<String> permissions = new ArrayList<String>();
            /***
             * 定位权限为必须权限，用户如果禁止，则每次进入都会申请
             */
            // 相机
            if(context.checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED){
                permissions.add(Manifest.permission.CAMERA);
            }
            if(context.checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED){
                permissions.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
            }


            if (permissions.size() > 0) {
                requestPermissions(permissions.toArray(new String[permissions.size()]), SDK_PERMISSION_REQUEST);
            }
        }
    }

    @TargetApi(23)
    private boolean addPermission(ArrayList<String> permissionsList, String permission) {
        if (context.checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) { // 如果应用没有获得对应权限,则添加到列表中,准备批量申请
            if (shouldShowRequestPermissionRationale(permission)){
                return true;
            }else{
                permissionsList.add(permission);
                return false;
            }

        }else{
            return true;
        }
    }

    @TargetApi(23)
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        // TODO Auto-generated method stub
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

    }


    private void initViews(){
        tmppicPath    = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM)+"/"+Constant.PRO_DIR+"/"+ Constant.UPLOAD_PIC_TEMP_NAME;
        cropedpicPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM)+"/"+Constant.PRO_DIR+"/"+Constant.UPLOAD_PIC_CROP_NAME;

        int Sviewwidth  = ScreenUtils.getScreenWidth(context);//
        pic_view_width  = (Sviewwidth-AppUtils.dip2px(context,10*3))/2;
        pic_view_hight  = pic_view_width/4*3;

        if(cert_type == 0){
            typeName.setText(getResources().getString(R.string.txt_sanzhengwuzheng));
            typelayout1.setVisibility(View.VISIBLE);
            typelayout2.setVisibility(View.GONE);
        }else{
            typeName.setText(getResources().getString(R.string.txt_yizhengyima));
            typelayout1.setVisibility(View.GONE);
            typelayout2.setVisibility(View.VISIBLE);
        }
    }

    private void initData(){
    }

    @Event(value={R.id.toTYPEModel,R.id.to_add,R.id.photo1,
            R.id.photo11,
            R.id.photo22,
            R.id.photo33,
            R.id.photo44,
            R.id.photo55})
    private void getEvent(View view){
        switch(view.getId()){

            case R.id.toTYPEModel:
                Dialog_cert_type();
                break;
            case R.id.to_add:
                if(checkinput()){
                    toNet_qyauthen();
                }
                break;
            case R.id.photo1:
                photoIndex = 0;
                Dialog_picsel();
                break;
            case R.id.photo11:
                photoIndex = 1;
                Dialog_picsel();
                break;
            case R.id.photo22:
                photoIndex = 2;
                Dialog_picsel();
                break;
            case R.id.photo33:
                photoIndex = 3;
                Dialog_picsel();
                break;
            case R.id.photo44:
                photoIndex = 4;
                Dialog_picsel();
                break;
            case R.id.photo55:
                photoIndex = 5;
                Dialog_picsel();
                break;

        }
    }

    private boolean checkinput(){
        if (put_shop_name.getText().toString().equals("")||put_social_code.getText().toString().equals("")||put_legal_person.getText().toString().equals("")|| put_legal_telphone.getText().toString().equals("")) {
            T.show(context, getResources().getString(R.string.alert_putisnotnull), 1);
            return false;
        } else {
            return true;
        }
    }

    public void Dialog_cert_type(){
        final Dialog dialog=new Dialog(context,R.style.customDialogStyle);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        View view= LayoutInflater.from(context).inflate(R.layout.dialog_cert_type, null);
        dialog.setContentView(view);
        view.findViewById(R.id.bt1).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                typeName.setText(getResources().getString(R.string.txt_sanzhengwuzheng));
                cert_type = 0;
                typelayout1.setVisibility(View.VISIBLE);
                typelayout2.setVisibility(View.GONE);
                dialog.dismiss();
            }
        });

        view.findViewById(R.id.bt2).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                typeName.setText(getResources().getString(R.string.txt_yizhengyima));
                cert_type = 1;
                typelayout1.setVisibility(View.GONE);
                typelayout2.setVisibility(View.VISIBLE);
                dialog.dismiss();
            }
        });

        view.findViewById(R.id.cancel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });

        Window dialogWindow = dialog.getWindow();
        dialogWindow.setWindowAnimations(R.style.commonAnimDialogStyle);
        dialogWindow.setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT);
        dialogWindow.setGravity(Gravity.BOTTOM);
        dialog.show();

    }

    public void Dialog_picsel(){
        final Dialog dialog=new Dialog(context,R.style.customDialogStyle);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        View view= LayoutInflater.from(context).inflate(R.layout.dialog_pic_sel, null);
        dialog.setContentView(view);
        view.findViewById(R.id.bt1).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                CheckPerission_CAMERA();
                dialog.dismiss();
            }
        });

        view.findViewById(R.id.bt2).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Intent.ACTION_PICK, null);
                intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, IMAGE_UNSPECIFIED);
                startActivityForResult(intent, PHOTO_ZOOM);
                dialog.dismiss();
            }
        });

        view.findViewById(R.id.cancel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });

        Window dialogWindow = dialog.getWindow();
        dialogWindow.setWindowAnimations(R.style.commonAnimDialogStyle);
        dialogWindow.setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT);
        dialogWindow.setGravity(Gravity.BOTTOM);
        dialog.show();

    }




    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == NONE)
            return;
        // 拍照
        if (requestCode == PHOTO_GRAPH) {
            startPhotoZoom(photoURI);
        }

        if (data == null)
            return;

        // 读取相册缩放图片
        if (requestCode == PHOTO_ZOOM) {
            startPhotoZoom(data.getData());
        }

        // 处理结果
        if (requestCode == PHOTO_RESOULT) {
            Bundle extras = data.getExtras();
            if (extras != null) {
                Bitmap photo = extras.getParcelable("data");
                saveCropedPhoto(photo);
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    ////////////////////////////////////////////////////////////////////////////////////剪裁图片
    /**
     * 收缩图片
     *
     * @param uri
     */
    public void startPhotoZoom(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");//调用Android系统自带的一个图片剪裁页面,
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            //添加这一句表示对目标应用临时授权该Uri所代表的文件
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        }
        intent.setDataAndType(uri, IMAGE_UNSPECIFIED);
        //        intent.putExtra("crop", "false");//进行修剪

        intent.putExtra("crop", "true");

        intent.putExtra("scale", true);
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 5);
        intent.putExtra("aspectY", 3);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", 450);
        intent.putExtra("outputY",270);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, PHOTO_RESOULT);
    }

    ////////////////////////////////////////////////////////////////////////////////////保存剪裁后的图片
    private void saveCropedPhoto(Bitmap bmp){
        try{
//            String cropedpicPath = this.cropedpicPath;
            File fImage = new File(this.cropedpicPath);
            fImage.createNewFile();
            FileOutputStream iStream = new FileOutputStream(fImage);
            bmp.compress(Bitmap.CompressFormat.PNG, 100, iStream);
            iStream.close();
            iStream =null;
            fImage =null;
            toNet_pic();

        }catch (Exception e){
            Logger.i("error...");
            e.printStackTrace();
        }

    }






    /**
     * 检测权限
     */
    private void CheckPerission_CAMERA() {

        if (Build.VERSION.SDK_INT >= 23){
            int checkCallPhonePermission = ContextCompat.checkSelfPermission(context, Manifest.permission.CAMERA);
//            Logger.i("showCameraAction = "  +checkCallPhonePermission);
            if(checkCallPhonePermission != PackageManager.PERMISSION_GRANTED){
                ActivityCompat.requestPermissions(mActivity,new String[]{Manifest.permission.CAMERA},Constant.REQUEST_TAKE_CAMERA_PERMISSION);
                return;
            }else{
                CheckPerission_STORAGE();
            }
        }else{
            CheckPerission_STORAGE();
        }
    }

    /**
     * 检测权限
     */
    private void CheckPerission_STORAGE() {
        if (Build.VERSION.SDK_INT >= 23){
            int checkCallPhonePermission = ContextCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE);
//            Logger.i("writeSTORAGEAction = "  +checkCallPhonePermission);
            if(checkCallPhonePermission != PackageManager.PERMISSION_GRANTED){
                ActivityCompat.requestPermissions(mActivity,new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},Constant.REQUEST_TAKE_STORAGE_PERMISSION);
                return;
            }else{
                createPhoto_path();
            }
        }else{
            createPhoto_path();
        }
    }

    //拍照的代码
    private void createPhoto_path() {
        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (takePictureIntent.resolveActivity(context.getPackageManager()) != null) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                //如果是7.0及以上的系统使用FileProvider的方式创建一个Uri
//                Logger.e("Build.VERSION.SDK_INT >= Build.VERSION_CODES.N");
                photoURI = v_2_4.get24MediaFileUri(context);
            } else {
//                Logger.e("7.0以下使用这种方式创建一个Uri");
                photoURI = v_2_4.getMediaFileUri(context);

            }
//            Logger.e("photoURI.getPath() = "+photoURI.getPath());
            //将Uri传递给系统相机
            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
            startActivityForResult(takePictureIntent, PHOTO_GRAPH);
        }
    }


















    ////////////////////////////////////////////////////////////////////////////////////NET_PIC
    public void toNet_pic() {
        hud.show();
        Logger.i("cropedpicPath=="+cropedpicPath);
        File file = new File(this.cropedpicPath);
        if (!file.exists())
        {
            T.show(context, "文件不存在，请修改文件路径", 1);
            return;
        }
        Map<String, String> params = new HashMap<>();
        params.put("type", ""+1);
        Map<String, String> headers = new HashMap<>();

        OkHttpUtils
                .post()
                .addFile("upfile", ""+Constant.UPLOAD_PIC_CROP_NAME, file)//
                .url(Constant.URL_upload_file)//
                .params(params)//
                .headers(headers)//
                .build()//
                .execute(pic_do);
    }
    StringCallback pic_do = new StringCallback(){
        @Override
        public void onError(Call call, Exception e, int i) {
            if(hud.isShowing()){
                hud.dismiss();
            }
            Logger.e(e.getMessage());
        }

        @Override
        public void onResponse(String s, int i) {
            if(hud.isShowing()){
                hud.dismiss();
            }
//            Logger.e(s);
            try{
                upload_bean data = new Gson().fromJson(s, upload_bean.class);
                if(data.state !=1 ){
                    T.show(context,data.msg,0);
                }else{
                    //do
                    switch (photoIndex){
                        case 0:
                            business_license = data.data;
                            PicassoUtils.Picasso_displayImage(context,Constant.IP+business_license,pic_view_width,pic_view_hight,photo1);
                            T.show(context,""+getResources().getString(R.string.alert_success_do),0);
                            break;
                        case 1:
                            business_license = data.data;
                            PicassoUtils.Picasso_displayImage(context,Constant.IP+business_license,pic_view_width,pic_view_hight,photo11);
                            T.show(context,""+getResources().getString(R.string.alert_success_do),0);
                            break;

                        case 2:
                            swdj_photo = data.data;
                            PicassoUtils.Picasso_displayImage(context,Constant.IP+swdj_photo,pic_view_width,pic_view_hight,photo22);
                            T.show(context,""+getResources().getString(R.string.alert_success_do),0);
                            break;
                        case 3:
                            zzjg_photo = data.data;
                            PicassoUtils.Picasso_displayImage(context,Constant.IP+zzjg_photo,pic_view_width,pic_view_hight,photo33);
                            T.show(context,""+getResources().getString(R.string.alert_success_do),0);
                            break;
                        case 4:
                            yhkh_photo = data.data;
                            PicassoUtils.Picasso_displayImage(context,Constant.IP+yhkh_photo,pic_view_width,pic_view_hight,photo44);
                            T.show(context,""+getResources().getString(R.string.alert_success_do),0);
                            break;
                        case 5:
                            quality_photo = data.data;
                            PicassoUtils.Picasso_displayImage(context,Constant.IP+quality_photo,pic_view_width,pic_view_hight,photo55);
                            T.show(context,""+getResources().getString(R.string.alert_success_do),0);
                            break;
                     }


                }
            }catch (Exception e){
                e.printStackTrace();
                T.show(context,getResources().getString(R.string.alert_again),0);
            }
        }
    };




    /////NET

    private void toNet_qyauthen(){
        hud.show();
        JSONObject jsonBody=new JSONObject();
        try {
            jsonBody.put("device_number",         AppUtils.get_device_id(context));
            jsonBody.put("device_type",           Constant.device_type);
            jsonBody.put("token",                 AppUtils.get_token(context));
            jsonBody.put("pageName",             "member");
            jsonBody.put("serviceName",          "qyauthen");

            jsonBody.put("member_id",              AppUtils.get_user_id(context));
            jsonBody.put("cert_type",             cert_type);
            jsonBody.put("shop_name",               put_shop_name.getText().toString());
            jsonBody.put("legal_person",            put_legal_person.getText().toString());
            jsonBody.put("legal_telphone",          put_legal_telphone.getText().toString());
            jsonBody.put("social_code",             put_social_code.getText().toString());
            jsonBody.put("business_license",       business_license);
            jsonBody.put("swdj_photo",             swdj_photo);
            jsonBody.put("zzjg_photo",             zzjg_photo);
            jsonBody.put("yhkh_photo",             yhkh_photo);
            jsonBody.put("quality_photo",          quality_photo);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        Logger.i(""+jsonBody.toString() +"["+Constant.URL_qyauthen+"]");
        HttpUtils.http_post_string(Constant.URL_qyauthen,jsonBody.toString(),do_qyauthen);
    }

    //////NET DO

    StringCallback do_qyauthen = new StringCallback(){


        @Override
        public void onError(Call call, Exception e, int i) {
            Logger.e(e.getMessage());
        }

        @Override
        public void onResponse(String s, int i) {
            if(hud.isShowing()){
                hud.dismiss();
            }
            Logger.e(s);
            try{
                newlist_bean data = new Gson().fromJson(s, newlist_bean.class);
                if(data.state !=1 ){
                    T.show(context,data.msg,0);
                }else{
                    T.show(context,""+getResources().getString(R.string.alert_success_tijiaorenzhengchenggong),1);
                }
            }catch (Exception e){
                e.printStackTrace();
                T.show(context,getResources().getString(R.string.alert_again),0);
            }
        }
    };
}
